package com.daxt.service.impl;

import java.awt.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.List;
import java.util.concurrent.Future;

import com.daxt.common.exception.BaseException;
import com.daxt.mapper.sys.ArchivesClassMapper;
import com.daxt.mapper.sys.WaterMarkMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.constant.FileExt;
import com.daxt.model.dic.*;
import com.daxt.model.dto.FileParam;
import com.daxt.model.dto.MountParamDto;
import com.daxt.model.service.archives.param.DirectMount;
import com.daxt.model.service.archives.vo.*;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.watermark.WaterMarkConfig;
import com.daxt.service.ArchivesService;
import com.daxt.service.UploadService;
import com.daxt.utils.*;
import com.daxt.utils.file.FileBaseUtil;
import com.daxt.utils.file.PdfUtils;
import com.daxt.utils.file.PoiUtil;
import com.daxt.utils.file.ToPdfUtil;
import com.itextpdf.text.BaseColor;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesTypeDocMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.model.service.archives.param.MountBathch;
import com.daxt.service.MountService;

import cn.hutool.core.util.ZipUtil;
import org.springframework.web.multipart.MultipartFile;

@Service
public class MountServiceImpl implements MountService {

    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private ArchivesClassMapper archivesClassMapper;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;
    @Autowired
    private ArchivesTypeDocMapper archivesTypeDocMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private WaterMarkMapper waterMarkMapper;

    private static int index = 0;

//    @Value(value = "${systemConfig.tempPath}")
//    private String basePath11;
//    @Value(value = "${systemConfig.tempPath}")
//    private String basePath;
    //    @Value(value = "${systemConfig.iso}")
//    private String iso;
//    @Value(value = "${systemConfig.ossDir}")
//    private String ossDir;
//    @Value(value = "${systemConfig.ossIpDoMain}")
//    private String domain;

    /**
     * @description: 改造批量挂接
     * @author: lig
     * @date: 2021/7/19
     */
    @Async("cloudExecutor")
    @Override
    public void mountBatchFile(MountBathch mountBathch, String taskId, ArchivesType archivesType) {

        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);
        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
//        String get32uuid1 = IdWorker.get32UUID();
        index = 0;

        QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<ArchivesDoc>();
        queryWrapper.in("id", mountBathch.getIds());
        List<ArchivesDoc> docList = archivesDocMapper.selectList(queryWrapper);
        if (docList == null || docList.size() == 0) {
            return;
        }

        try {



            File file = new File(tempPath + taskId);
            if (!file.exists())
                file.mkdirs();
            ZipUtil.unzip(new File(ossDir + mountBathch.getFileUrl()), file, Charset.forName("GBK"));
//            ZipUtil.unzip(new File(ossDir + mountBathch.getFileUrl()), file, Charset.forName("GBK"));
            File[] listFiles = file.listFiles();
            if (listFiles == null || listFiles.length < 1) {
                redisUtil.set(taskId, "3:" + "zip包内未找到相应内容 ", 60 * 5);
                return;
            }
            //卷件模式
            String pattern = mountBathch.getType();

            List<MountParamDto> dossDocs = new ArrayList<>();
            for (File tempFile : listFiles) {

                docList.forEach((ArchivesDoc aDoc) -> {

                    //卷模式
                    if (DicDocPattern.PATTERN_1.getKey().equals(pattern)) {
                        QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
                        queryWrapperDoc.in("dossierId", aDoc.getId());
                        queryWrapperDoc.eq("dossierNum", FileBaseUtil.getFileNameFront(tempFile.getName()));
                        queryWrapperDoc.eq("isDelete", "0");
                        List<ArchivesDoc> docListByDossier = archivesDocMapper.selectList(queryWrapperDoc);
                        if (tempFile.isDirectory()) {
                            File[] files = tempFile.listFiles();//获取件
                            for (File tFile : files) {
                                docListByDossier.forEach((ArchivesDoc dossierDoc) -> {
                                    if (!matchingMount(dossierDoc, tFile, taskId,mountBathch.getUserId())) return;
                                });
                            }
                        }
                    } else if (DicDocPattern.PATTERN_0.getKey().equals(pattern)) {
                        if (!matchingMount(aDoc, tempFile, taskId,mountBathch.getUserId())) return;
                    } else {
                        redisUtil.set(taskId, "3:" + "模式（卷/件）不匹配", 60 * 5);
                    }


                });
//
            }


        } catch (Exception e) {
            e.printStackTrace();
            redisUtil.set(taskId, "2", 60 * 5);
        }
        redisUtil.set(taskId, "1:" + index, 60 * 5);

    }

    @Async("cloudExecutor")
    @Override
    public Future<String> createIos(String typeId, List<String> ids, String path, String taskId, String model, String fileType, String classId,String fondsId) {

        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
        String tempFileShuiYin = ossDir + BaseConstants.BUCKET_TEMP_NAME + "/" + IdWorker.getIdStr();
        String iso_dir = RedisUtil.getSysConfig(SystemConfigType.ISO_DIR);
        String exportFileDirectory = RedisUtil.getSysConfig(SystemConfigType.EXPORT_FILE_DIRECTORY);

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);



        if ("0".equals(model)) {
            QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc = new QueryWrapper<ArchivesTypeDoc>();
            queryWrapperTypeDoc.eq("typeId", typeId);
            queryWrapperTypeDoc.eq("isImport", "1");
            queryWrapperTypeDoc.eq("extType", "doc");
            QueryWrapper<ArchivesDoc> queryWrapperList = new QueryWrapper<ArchivesDoc>();
            queryWrapperList.in("id", ids);
            // add by lig 2021-07-05  解决生成iso包含回收站数据bug
            queryWrapperList.eq("isDelete", "0");
            queryWrapperList.orderByAsc("itemNum");

            List<ArchivesTypeDoc> typeDoc = archivesTypeDocMapper.selectList(queryWrapperTypeDoc);
            String[] header = new String[typeDoc.size()];
            List<String[]> data = new ArrayList<String[]>();

            List<ArchivesDoc> docEntity = archivesDocMapper.selectList(queryWrapperList);
            for (ArchivesDoc archivesDoc : docEntity) {
                //孝义版本展示分类号最后一级
                if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_3)) {
                    ArchivesUtil.builClassNum(archivesDoc);
                }
                String[] value = new String[header.length];
                for (int i = 0; i < header.length; i++) {
                    header[i] = typeDoc.get(i).getColumnComment();
                    Map<String, Object> beanToMap = JSON.parseObject(JSON.toJSONString(archivesDoc), Map.class);
                    Object object = beanToMap.get(typeDoc.get(i).getExtColumn());
                    value[i] = (object == null ? "" : object.toString());
                }
                String archivalNum = StringUtils.isEmpty(archivesDoc.getArchivalNum()) ? archivesDoc.getId() + ""
                        : archivesDoc.getArchivalNum();
                String categoryNum = StringUtils.isEmpty(archivesDoc.getCategoryNum()) ? archivesDoc.getId() + ""
                        : archivesDoc.getCategoryNum();
                String archivalYear = StringUtils.isEmpty(archivesDoc.getArchivalYear()) ? archivesDoc.getId() + ""
                        : archivesDoc.getArchivalYear();
                String itemNum = StringUtils.isEmpty(archivesDoc.getItemNum()) ? archivesDoc.getId() + ""
                        : archivesDoc.getItemNum();
                QueryWrapper<ArchivesDocFile> queryWrapperFile = new QueryWrapper<ArchivesDocFile>();
                queryWrapperFile.eq("docId", archivesDoc.getId());
                List<ArchivesDocFile> fileList = archivesDocFileMapper.selectList(queryWrapperFile);
                for(int i=0;i<fileList.size();i++){
                    String fileUrl = fileList.get(i).getFileUrl();
                    File file =uploadService.gainFile(fileUrl);
                    String dir=path + "/" + itemNum + "/" ;
                    //System.out.println("新文件路径："+dir);

                    String ext= FileBaseUtil.getFileNameExt(file.getName());
                    //生成水印
                    tempFileShuiYin=getShuiYinPath(tempFileShuiYin ,file,fondsId);
                    try {
                        FileUtils.copyFile(new File(tempFileShuiYin), new File( dir + fileUrl.substring(fileUrl.lastIndexOf("/")+1)));
                    } catch (IOException io) {
                        io.printStackTrace();
                    }
                }

                data.add(value);
            }
            try {
                PoiUtil.exportD(data, header, "导出", path, "件");
            } catch (IOException e) {
                e.printStackTrace();
                e.printStackTrace();
                redisUtil.set(taskId, "2", 60 * 5);
            }
        } else if ("1".equals(model)) {
            QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc = new QueryWrapper<ArchivesTypeDoc>();
            queryWrapperTypeDoc.eq("typeId", typeId);
            queryWrapperTypeDoc.eq("isImport", "1");
            queryWrapperTypeDoc.eq("extType", "dossier");
            QueryWrapper<ArchivesDoc> queryWrapperList = new QueryWrapper<ArchivesDoc>();
            queryWrapperList.in("id", ids);
            // add by lig 2021-07-05  解决生成iso包含回收站数据bug
            queryWrapperList.eq("isDelete", "0");
            queryWrapperList.orderByAsc("dossierNum");

            List<ArchivesTypeDoc> typeDoc = archivesTypeDocMapper.selectList(queryWrapperTypeDoc);
            String[] header = new String[typeDoc.size()];
            List<String[]> data = new ArrayList<String[]>();

            List<ArchivesDoc> docEntity = archivesDocMapper.selectList(queryWrapperList);
            for (ArchivesDoc archivesDoc : docEntity) {
                String[] value = new String[header.length];
                for (int i = 0; i < header.length; i++) {
                    header[i] = typeDoc.get(i).getColumnComment();
                    Map<String, Object> beanToMap = JSON.parseObject(JSON.toJSONString(archivesDoc), Map.class);
                    Object object = beanToMap.get(typeDoc.get(i).getExtColumn());
                    value[i] = (object == null ? "" : object.toString());
                }
                data.add(value);
            }
            try {
                PoiUtil.exportD(data, header, "导出", path, "卷");
            } catch (IOException e1) {
                e1.printStackTrace();
                redisUtil.set(taskId, "2", 60 * 5);
            }
            // ---------------------
            QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc1 = new QueryWrapper<ArchivesTypeDoc>();
            queryWrapperTypeDoc1.eq("typeId", typeId);
            queryWrapperTypeDoc1.eq("isImport", "1");
            queryWrapperTypeDoc1.eq("extType", "doc");
            QueryWrapper<ArchivesDoc> queryWrapperList1 = new QueryWrapper<ArchivesDoc>();
            queryWrapperList1.in("dossierId", ids);
            queryWrapperList1.orderByAsc("itemNum");
            List<ArchivesTypeDoc> typeDoc1 = archivesTypeDocMapper.selectList(queryWrapperTypeDoc1);
            String[] header1 = new String[typeDoc1.size()];
            List<String[]> data1 = new ArrayList<String[]>();
            if (typeDoc1 != null && typeDoc1.size() > 0) {
                List<ArchivesDoc> docEntity1 = archivesDocMapper.selectList(queryWrapperList1);
                for (ArchivesDoc archivesDoc : docEntity1) {
                    QueryWrapper<ArchivesDocFile> queryWrapperFile = new QueryWrapper<ArchivesDocFile>();
                    queryWrapperFile.eq("docId", archivesDoc.getId());
                    List<ArchivesDocFile> fileList = archivesDocFileMapper.selectList(queryWrapperFile);
                    String[] value = new String[header1.length];
                    for (int i = 0; i < header1.length; i++) {
                        header1[i] = typeDoc1.get(i).getColumnComment();
                        Map<String, Object> beanToMap = JSON.parseObject(JSON.toJSONString(archivesDoc), Map.class);
                        Object object = beanToMap.get(typeDoc1.get(i).getExtColumn());
                        value[i] = (object == null ? "" : object.toString());
                    }

                    //处理卷下的文件
                    for(ArchivesDocFile docFile: fileList) {
                        String itemNum = StringUtils.isEmpty(archivesDoc.getItemNum()) ? archivesDoc.getId() + "---"
                                : archivesDoc.getItemNum();
                        String fileUrl = docFile.getFileUrl();
                        try {
                            //String dir = path + "/" + archivalNum + "/" + categoryNum + "/" + archivesDoc.getDossierNum() + "/";
                            String dir = path + "/" + archivesDoc.getDossierNum() + "/" + itemNum + "/";
                            File tempFile = new File(dir);
                            if (!tempFile.exists())
                                tempFile.mkdirs();


                            File file =uploadService.gainFile(fileUrl);

                            //生成水印
                            tempFileShuiYin=getShuiYinPath(tempFileShuiYin ,file,fondsId);

                            //记得处理生成水印的pdf文件
                            FileUtils.copyFile(new File(tempFileShuiYin), new File(dir  + fileUrl.substring(fileUrl.lastIndexOf("/")+1)));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    data1.add(value);
                }
            }
            try {
                PoiUtil.exportD(data1, header1, "导出", path, "件");
            } catch (IOException e) {
                e.printStackTrace();
                redisUtil.set(taskId, "2", 60 * 5);
            }
        }


        // path
        String tar = exportFileDirectory + year+ "/" + month + "/" + day;
        if("iso".equals(fileType)){//生成iso文件
            try {
                //String tar = tempPath + taskId + "_doc.iso";
                StringBuilder exportFileName=new StringBuilder();
                ArchivesType archivesType = archivesTypeMapper.selectById(typeId);
                String typeName = archivesType.getTypeName();
                exportFileName.append(typeName);
                String name=exportFileName(exportFileName,classId);
                name=getZipName(name);
                tar=tar.replace("/","\\");
                File file=new File(tar);
                if(!file.exists()){
                    file.mkdirs();
                }
                tar = tar + "/" + name + ".iso";
                if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                    path=path.replace("/","\\");
                    //tar=tar.replace("/","\\");
                    iso_dir=iso_dir.replace("/","\\");
                    String str = iso_dir + "ultraiso -imax -l -f " + path + " -volu TEST_CD -out " + tar;
//                String str = iso + "ultraiso -imax -l -f " + path + " -volu TEST_CD -out " + tar;
                    System.err.println("str:"+str);
                    Process prc = Runtime.getRuntime().exec(str);
                    prc.waitFor();
                } else {
                    String str = "mkisofs -jcharset utf8 -o " + tar + " " + path;
                    Process prc = Runtime.getRuntime().exec(str);
                    prc.waitFor();
                }
                String uploadFile = FileCopyUtil.uploadFile("temp", IdWorker.getIdStr() + "_doc.iso", new FileInputStream(tar), ossDir);
                redisUtil.set(taskId, "1:" + uploadFile, 60 * 5);
            } catch (Exception e) {
                e.printStackTrace();
                redisUtil.set(taskId, "2", 60 * 5);
            }
        }else{//生成zip文件

            StringBuilder exportFileName=new StringBuilder();
            ArchivesType archivesType = archivesTypeMapper.selectById(typeId);
            String typeName = archivesType.getTypeName();
            exportFileName.append(typeName);
            String name=exportFileName(exportFileName,classId);
            name=getZipName(name);

            File file=new File(tar);
            if(!file.exists()) file.mkdirs();
            //exportFile
            String zipPath=tar+"/"+name+".zip";

            com.daxt.utils.ZipUtil.zipFile(path,zipPath);

            tar=zipPath;
        }
        return new AsyncResult<>(tar);
    }

    private String getShuiYinPath(String tempFileShuiYin , File file ,String fondsId){
        String waterMarkStr =  RedisUtil.getSysConfig(SystemConfigType.WATER_MARK).trim();
        String waterMarkSize =  RedisUtil.getSysConfig(SystemConfigType.WATER_MARK_SIZE).trim();

        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5 )){
            if(!StringUtils.isEmpty(fondsId)){
                QueryWrapper<WaterMarkConfig> wrapper=new QueryWrapper<>();
                wrapper.eq("fondsId",fondsId);
                WaterMarkConfig waterMark = waterMarkMapper.selectOne(wrapper);
                if(waterMark!=null){
                    waterMarkStr=waterMark.getWaterMark();
                    waterMarkSize=waterMark.getWaterMarkSize();
                }
            }
        }

        int R = 187;
        int G = 187;
        int B = 187;
        String ext= FileBaseUtil.getFileNameExt(file.getName());
        if("pdf".equals(ext)){
            tempFileShuiYin = tempFileShuiYin + ".pdf";
            WaterMarkUtil.waterMark(file.getAbsolutePath(),
                    tempFileShuiYin, waterMarkStr,new BaseColor(R,G,B),waterMarkSize);
        }else if (FileBaseUtil.isImg(ext)){
            tempFileShuiYin = tempFileShuiYin + ".jpg";
            WaterMarkUtil.mark(file.getAbsolutePath(),
                    tempFileShuiYin, new Color(R, G, B), waterMarkStr);
        }else{
            tempFileShuiYin=file.getAbsolutePath();
        }
        return tempFileShuiYin;
    }

    private String getZipName(String name){
        if(name.endsWith("-")){
            name=name.substring(0,name.lastIndexOf("-"));
            return getZipName(name);
        }else {
            return name;
        }
    }

    private String exportFileName(StringBuilder exportFileName,String classId){
        ArchivesClass archivesClass = archivesClassMapper.selectById(classId);

        if(archivesClass==null){
            return exportFileName.toString();
        }
        if(archivesClass.getParentId()==0){

            exportFileName.append("-").insert(exportFileName.indexOf("-")+1,archivesClass.getClassName()+"-");

            return exportFileName.toString();
        }else{
            exportFileName.append("-").insert(exportFileName.indexOf("-")+1,archivesClass.getClassName()+"-");

            return exportFileName(exportFileName,archivesClass.getParentId()+"");
        }
    }



    /**
     * @description: 改造挂接文件
     * @author: lig
     * @date: 2021/7/19
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> mountFile(ArchivesDocFile archivesDocFile) {


        String sysHome = RedisUtil.getSysConfig(SystemConfigType.SYS_HOME);
        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);
        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);

        String get32uuid = IdWorker.get32UUID();
        String fileUrl = archivesDocFile.getFileUrl();
        if (StringUtils.isEmpty(fileUrl)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件不能为空！！！", null);
        }

        ArchivesDoc selectById = archivesDocMapper.selectById(archivesDocFile.getDocId());

        if (selectById == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "案件不存在！！！", null);
//        } else if (StringUtils.isEmpty(selectById.getFondsId())) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "全宗不存在！！！", null);
//        } else if (StringUtils.isEmpty(selectById.getTypeNum())) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "门类号不存在！！！", null);
//        } else if (StringUtils.isEmpty(selectById.getCategoryNum())) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "类目号不存在！！！", null);
//        } else if (StringUtils.isEmpty(selectById.getItemNum())) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号不存在！！！", null);
//        }
        } else if (StringUtils.isEmpty(selectById.getFileType())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在！！！", null);
        }

        //add lig 2021-07-30 散文件不校验件号
        if (!selectById.getFileType().equals("scattered")) {
            if (StringUtils.isEmpty(selectById.getItemNum())) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号不存在！！！", null);
            }

        }

        String filePath = "";
        try {
            String basePath11 = tempPath;

            String newName = selectById.getItemNum();
            File downFile = new File(ossDir + fileUrl);

            if (downFile.getAbsolutePath().toLowerCase().endsWith("zip".toLowerCase())) {
                try {
                    ZipUtil.unzip(downFile, new File(basePath11 + get32uuid + File.separator), Charset.forName("GBK"));
                } catch (Exception e) {
                    return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "解压异常！！！", null);
                }
                File zipFile = new File(basePath11 + get32uuid + File.separator);
                File[] files = zipFile.listFiles();
                for (File file : files) {
                    //edit by lig 2021-07-21
                    buildFile(new MountParamDto(file, selectById, DicDocPattern.PATTERN_0.getKey(),archivesDocFile.getUserId()));

                }
            }else if (downFile.isFile() || downFile.getAbsolutePath().indexOf(".") > 0) {
                if(archivesDocFile.getIsRealName()!=null && archivesDocFile.getIsRealName()){
                    buildFile(new MountParamDto(downFile, selectById, DicDocPattern.PATTERN_0.getKey(),true,archivesDocFile.getFileName(),archivesDocFile.getUserId()));
                }else{
                    buildFile(new MountParamDto(downFile, selectById, DicDocPattern.PATTERN_0.getKey(),archivesDocFile.getUserId()));
                    // buildFile(downFile, selectById, DicDocPattern.PATTERN_0.getKey());
                }
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "挂接成功！！！", null);
            }


        } catch (BaseException be) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), be.getMsg().toString(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "挂接失败！！！", null);
        }


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }


    /**
     * @description: 基础挂接文件
     * @author: lig
     * @date: 2021/7/19
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> baseMountFile(ArchivesDocFile archivesDocFile) {

        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);

        String get32uuid = IdWorker.get32UUID();
        String fileUrl = archivesDocFile.getFileUrl();
        if (StringUtils.isEmpty(fileUrl)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件不能为空！！！", null);
        }

        ArchivesDoc selectById = archivesDocMapper.selectById(archivesDocFile.getDocId());

        if (selectById == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "案件不存在！！！", null);
        } else if (StringUtils.isEmpty(selectById.getFileType())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在！！！", null);
        }

        try {
            File downFile = new File(ossDir + fileUrl);
            if (downFile.isFile() || downFile.getAbsolutePath().indexOf(".") > 0) {

                boolean isFileRealName=false;
                if(archivesDocFile.getIsRealName()==null ? false:archivesDocFile.getIsRealName()){ //当为true时，使用文件本来的名称
                    isFileRealName=true;
                }
                buildFile(new MountParamDto(downFile, selectById, DicDocPattern.PATTERN_0.getKey(),false,isFileRealName,archivesDocFile.getFileName(),archivesDocFile.getIsOA()));
//                buildFile(downFile, selectById, DicDocPattern.PATTERN_0.getKey());
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "挂接成功！！！", null);
            }


        } catch (BaseException be) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), be.getMsg().toString(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "挂接失败！！！", null);
        }


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<String> MountWiaacmgrFile(ArchivesDoc aDoc, MultipartFile file,File saveFile,String userId) {

        if ( file.isEmpty()) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件不能为空！！！", null);
        }

        try {
            if(saveFile==null){
                customUploadFile(file,aDoc,file.getOriginalFilename());
            }else{
                customUploadFile(saveFile, aDoc, FileBaseUtil.getFileNameFront(file.getOriginalFilename()) + ".pdf",userId);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "挂接失败！！！", null);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }





    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> directMountFile(DirectMount directmount) {

        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);


        String get32uuid1 = IdWorker.get32UUID();
        File file = new File(tempPath + get32uuid1);
        if (!file.exists())
            file.mkdirs();
        ZipUtil.unzip(new File(ossDir + directmount.getFilePath()), file, Charset.forName("GBK"));
        File[] listFiles = file.listFiles();
        if (listFiles == null || listFiles.length < 1) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "zip包内未找到相应内容", null);
        }

        for (File tempFile : listFiles) {
            if(tempFile.isDirectory()){
                File[] docFiles = tempFile.listFiles();
                for (File docFile : docFiles) {
                        String year = tempFile.getName();

                        ArchivesDoc aDocNew = new ArchivesDoc();
                        aDocNew.setFondsId(directmount.getFondsId());
                        aDocNew.setTypeNum(directmount.getTypeNum());
                        aDocNew.setClassNum(directmount.getClassNum());
                        aDocNew.setArchivalYear(year);
//                        aDocNew.setFileType("dossier");
                        aDocNew.setFileType(DicDocFileType.DOC.getKey());
                        aDocNew.setTitle(year);
                        aDocNew.setState(DicDocState.neaten.getKey());
                        aDocNew.setIsDelete(BaseConstants.DELETE_NORMAL);
                        archivesDocMapper.insert(aDocNew);
                        customUploadFile(docFile, aDocNew, docFile.getName(),null);

                }
            }

        }






        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }








    /**
     * @description: 上传文件
     * @param fileName  例：xxx.pdf
     * @author: lig
     * @date: 2021/6/21
     */
    private String customUploadFile(File saveFile, ArchivesDoc aDoc, String fileName,String userId) throws BaseException, IOException {

        if(!saveFile.isFile()){throw new BaseException(ResultCode.RESULT_ERROR.getCode(),"请确认是文件 ， "+saveFile.getName()+"");}

        FileInputStream inputStream = new FileInputStream(saveFile.getAbsolutePath());

        String extName = FileBaseUtil.getFileExtName(saveFile);
        String filePath = ArchivesUtil.buildFilePath(aDoc,fileName);
//      String fileUrl = buildFileUrl(aDoc, newName, extName);


        FileParam fp = new FileParam("static", filePath, inputStream, FileBaseUtil.getContentType(saveFile.getAbsolutePath()));

        String fileUrl = uploadService.upload(fp);
        if(StringUtils.isEmpty(fileUrl)) throw new BaseException(ResultCode.RESULT_ERROR.getCode(), "附件上传失败" );

//      String fileUrl = FileBaseUtil.upload(fp);

        long fileSize = saveFile.length();

        ArchivesDocFile archivesDocFile = new ArchivesDocFile( aDoc.getId(), fileName, FileBaseUtil.obtainFileType(extName), extName, fileUrl,String.valueOf(fileSize),userId);
        int row=archivesDocFileMapper.insert(archivesDocFile);

        /*if(row>0){
            Integer mountPage = aDoc.getMountPage();
            if(mountPage !=null && mountPage>0){
                Integer page = aDoc.getPages() == null || "".equals(aDoc.getPages()) ? 0: Integer.parseInt(aDoc.getPages());
                page += mountPage;
                aDoc.setPages(page.toString());
                archivesDocMapper.updateById(aDoc);

                QueryWrapper<ArchivesDoc> docQueryWrapper=new QueryWrapper<>();
                docQueryWrapper.eq("id",aDoc.getDossierId());
                ArchivesDoc doss = archivesDocMapper.selectOne(docQueryWrapper);
                if(doss != null){
                    Integer dossPage = doss.getPages() == null || "".equals(doss.getPages()) ? 0: Integer.parseInt(doss.getPages());
                    dossPage += mountPage;
                    doss.setPages(dossPage.toString());
                    archivesDocMapper.updateById(doss);
                }
            }
        }*/


        index++;
        return fileUrl;
    }

    /**
     * @description: 上传文件  MultipartFile
     * @author: lig
     * @date: 2021/6/21
     */
    private String customUploadFile(MultipartFile saveFile, ArchivesDoc aDoc, String newName) throws Exception {


        String fileName = StringUtils.isEmpty(newName)?saveFile.getOriginalFilename():newName;

        String extName = FileBaseUtil.getFileNameExt(saveFile.getOriginalFilename());
        String fileUrl = buildFileUrl(aDoc, fileName, extName);


        FileParam fp = new FileParam("static", fileUrl, saveFile.getInputStream(), saveFile.getContentType());
        String filePath = uploadService.upload(fp);
        long fileSize = saveFile.getSize();


        ArchivesDocFile archivesDocFile = new ArchivesDocFile( aDoc.getId(), fileName, FileBaseUtil.obtainFileType(extName), extName, filePath,String.valueOf(fileSize));
        archivesDocFileMapper.insert(archivesDocFile);
        index++;
        return filePath;


    }


    /**
     * @description: 根据模式构造url地址
     * @author: lig
     * @date: 2021-06-21
     */
    private String buildFileUrl(ArchivesDoc aDoc, String newName, String extName) {
        StringBuffer fileUrl = new StringBuffer();
        String u = "/";
        fileUrl.append(aDoc.getFondsNum());
        fileUrl.append(u);
        fileUrl.append(aDoc.getTypeNum());
        fileUrl.append(u);
        fileUrl.append(aDoc.getCategoryNum());
        fileUrl.append(u);
        fileUrl.append(aDoc.getDossierNum());
        if (!StringUtils.isEmpty(aDoc.getItemNum())) {
            fileUrl.append(u);
            fileUrl.append(aDoc.getItemNum());

        }
        fileUrl.append(u);
        fileUrl.append(newName);


        if (fileUrl.indexOf(".") < 1) {
            fileUrl.append(".");
            fileUrl.append(extName);
        }


        return fileUrl.toString();

    }




//    /**
//     * @description: 构造文件 上传
//     * @author: lig
//     * @date: 2021/7/19
//     */
//
//    private void buildFile(MountParamDto mpDto) throws Exception {
//
//
//        ////        //删除旧附件
//        //        QueryWrapper<ArchivesDocFile> wrapperDel = new QueryWrapper<ArchivesDocFile>();
//        //        wrapperDel.eq("docId", doc.getId());
//        //        archivesDocFileMapper.delete(wrapperDel);
//
//        File tempFile = mpDto.getTempFile();
//        ArchivesDoc doc = mpDto.getDoc();
//        String pattern = mpDto.getPattern();
//
//
//        //新文件名 包含扩展名    目录pdf
//        String newName = archivesService.buildFileName(tempFile, doc, pattern);
//        newName = notRepeat(doc, newName);
//        String ext = FileBaseUtil.getFileExtName(tempFile);
//
//
//
//        if (FileBaseUtil.getFileExtName(tempFile).equalsIgnoreCase("zip")) {
//
//            File fileZip = new File(SystemConfig.tempPath + new Random().nextInt(1000) + System.currentTimeMillis());
//            if (!fileZip.exists())
//                fileZip.mkdirs();
//            ZipUtil.unzip(tempFile, fileZip, Charset.forName("GBK"));
//            File[] listZipFiles = fileZip.listFiles();
//            for (File fZip : listZipFiles) {
//                buildFile(new MountParamDto(fZip, doc, pattern));
//            }
//
//        }else if (tempFile.isDirectory()) { //目录
//            File saveFile = ArchivesUtil.builImgToPdfFile(tempFile, doc, pattern, newName);
//
//            if (saveFile != null){
//                //改造 lig  2021-06-21
//                String absolute = customUploadFile(saveFile, doc, newName);
//                return;
//
//            }
//
//        }else if (FileBaseUtil.getFileExtName(tempFile).equalsIgnoreCase(FileExt.doc.getDesc()) || FileBaseUtil.getFileExtName(tempFile).equalsIgnoreCase(FileExt.docx.getDesc())) { // 其他格式附件
////            String outPdf = SystemConfig.tempPath + IdWorker.get32UUID() + "/";
////            String outPdf = SystemConfig.tempPath + absolute.substring(0, absolute.lastIndexOf("/"));
//            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");
//            String tempPath3 = FileBaseUtil.getFileNameFront(FileBaseUtil.getPathFileName(tempFile.getAbsolutePath()));
//            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("/") + 1);
//            WordUtil.toPdf(tempFile.getAbsolutePath(), outPdf);
//
////            String pdfPath = ToPdfUtil.excel2pdf(tempFile.getAbsolutePath(), absolute);
//            File docPdfFile = new File( tempPath3 +".pdf");
//            customUploadFile(tempFile, doc, FileBaseUtil.getFileNameFront(newName) + ".docx");
//            customUploadFile(docPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf");
//
//
//            //新方法
////            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");
////            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("/") + 1);
////
//////            String pdfPath = ToPdfUtil.excel2pdf(outPdf);
////            String pdfPath = ToPdfUtil.wordTopdf(tempFile.getAbsolutePath(), tempPath2);
////            File excelPdfFile= new File(pdfPath);
////            customUploadFile(excelPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf");
//
//
//
//        } else if (ext.equalsIgnoreCase(FileExt.xls.getDesc()) || ext.equalsIgnoreCase(FileExt.xlsx.getDesc())) { // excel格式附件
//
//            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");
//            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("/") + 1);
//
////            String pdfPath = ToPdfUtil.excel2pdf(outPdf);
//            String pdfPath = ToPdfUtil.excel2pdf(tempFile.getAbsolutePath(), tempPath2);
//            File excelPdfFile= new File(pdfPath);
//            customUploadFile(excelPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf");
//
//
//
//        }else{
//            String uploadFileUrl = customUploadFile(tempFile, doc, newName);
//        }
//
//
//    }


    /**
     * @description: 构造文件 上传
     * @author: lig
     * @date: 2021/7/19
     */
    private void buildFile(MountParamDto mpDto) throws Exception {


        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);
        ////        //删除旧附件
        //        QueryWrapper<ArchivesDocFile> wrapperDel = new QueryWrapper<ArchivesDocFile>();
        //        wrapperDel.eq("docId", doc.getId());
        //        archivesDocFileMapper.delete(wrapperDel);

        File tempFile = mpDto.getTempFile();
        ArchivesDoc doc = mpDto.getDoc();
        String pattern = mpDto.getPattern();
        String userId=mpDto.getUserId();


        String newName = tempFile.getName();
        if(mpDto.getIsRechristen() == true){
            //新文件名 包含扩展名    目录pdf
            newName = archivesService.buildFileName(tempFile, doc, pattern);
            newName = notRepeat(doc, newName);
        }
        if(mpDto.getIsFileRealName()!=null && mpDto.getIsFileRealName()==true){
            newName=mpDto.getFileRealName();
        }
        String ext = FileBaseUtil.getFileExtName(tempFile);

        if (FileBaseUtil.getFileExtName(tempFile).equalsIgnoreCase("zip")) {
            File fileZip = new File(tempPath + new Random().nextInt(1000) + System.currentTimeMillis());
            if (!fileZip.exists())
                fileZip.mkdirs();
            ZipUtil.unzip(tempFile, fileZip, Charset.forName("GBK"));
            File[] listZipFiles = fileZip.listFiles();
            for (File fZip : listZipFiles) {
                buildFile(new MountParamDto(fZip, doc, pattern,userId));
            }

        }else if (tempFile.isDirectory()) { //目录
            File saveFile = ArchivesUtil.builImgToPdfFile(tempFile, doc, pattern, newName);

            if (saveFile != null){
                //改造 lig  2021-06-21
                String absolute = customUploadFile(saveFile, doc, newName,userId);
                return;

            }

        }else if (FileBaseUtil.getFileExtName(tempFile).equalsIgnoreCase(FileExt.doc.getDesc()) || FileBaseUtil.getFileExtName(tempFile).equalsIgnoreCase(FileExt.docx.getDesc())) { // 其他格式附件
            //如果是从oa系统获取的doc文件将直接进行上传，不转换为pdf了。
            /*if(mpDto.getIsOA()){
                String uploadFileUrl = customUploadFile(tempFile, doc, newName,userId);
                return;
            }*/

//            String outPdf = SystemConfig.tempPath + IdWorker.get32UUID() + "/";
//            String outPdf = SystemConfig.tempPath + absolute.substring(0, absolute.lastIndexOf("/"));
            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");

            String tempPath3 = FileBaseUtil.getFileNameFront(FileBaseUtil.getPathFileName(tempFile.getAbsolutePath()));
            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("/") + 1);
            WordUtil.toPdf(tempFile.getAbsolutePath(), outPdf);
//            String pdfPath = ToPdfUtil.excel2pdf(tempFile.getAbsolutePath(), absolute);


            ToPdfUtil.doc2pdf(tempPath2,tempPath3 +".pdf");

            File docPdfFile = new File( tempPath3 +".pdf");
            //customUploadFile(tempFile, doc, FileBaseUtil.getFileNameFront(newName) + ".docx");

            //获取文件的页数
            //Integer page= PdfUtils.getPdfPageCount(docPdfFile.getAbsolutePath());
            //doc.setMountPage(page);

            customUploadFile(docPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf",userId);


            //新方法
//            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");
//            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("/") + 1);
//
////            String pdfPath = ToPdfUtil.excel2pdf(outPdf);
//            String pdfPath = ToPdfUtil.wordTopdf(tempFile.getAbsolutePath(), tempPath2);
//            File excelPdfFile= new File(pdfPath);
//            customUploadFile(excelPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf");



        } else if (ext.equalsIgnoreCase(FileExt.xls.getDesc()) || ext.equalsIgnoreCase(FileExt.xlsx.getDesc())) { // excel格式附件
            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");
            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("/") + 1);

//            String pdfPath = ToPdfUtil.excel2pdf(outPdf);
            String pdfPath = ToPdfUtil.excel2pdf(tempFile.getAbsolutePath(), tempPath2);
            File excelPdfFile= new File(pdfPath);

            //获取文件的页数
            //Integer page= PdfUtils.getPdfPageCount(excelPdfFile.getAbsolutePath());
            //doc.setMountPage(page);

            customUploadFile(excelPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf",userId);

        } else if (ext.equalsIgnoreCase(FileExt.img_jpg.getDesc()) || ext.equalsIgnoreCase(FileExt.img_png.getDesc())
                || ext.equalsIgnoreCase(FileExt.img_tif.getDesc()) || ext.equalsIgnoreCase(FileExt.img_tiff.getDesc())
                || ext.equalsIgnoreCase(FileExt.img_jpeg.getDesc()) || ext.equalsIgnoreCase(FileExt.img_gif.getDesc())){ // jpg、png、tif、jpeg、gif格式附件
            String tempPath2 = tempFile.getAbsolutePath().replaceAll("\\\\","/");
            String outPdf = tempPath2.substring(0, tempPath2.lastIndexOf("."));

            PdfUtils.oneImgToPdf(tempFile.getAbsolutePath(), outPdf+".pdf");
            File excelPdfFile= new File(outPdf+".pdf");

            //获取文件的页数
            //Integer page= PdfUtils.getPdfPageCount(excelPdfFile.getAbsolutePath());
            //doc.setMountPage(page);

            customUploadFile(excelPdfFile, doc, FileBaseUtil.getFileNameFront(newName) + ".pdf",userId);

        }else{

            /*if(ext.equalsIgnoreCase(FileExt.pdf.getDesc())){
                Integer page= PdfUtils.getPdfPageCount(tempFile.getAbsolutePath());
                doc.setMountPage(page);
            }else{
                doc.setMountPage(1);
            }*/



            String uploadFileUrl = customUploadFile(tempFile, doc, newName,userId);
        }


    }

    /**
     * @description: 挂接匹配
     * @author: lig
     * @date: 2021/7/20
     */
    private boolean mountMatching(ArchivesDoc doc, String fileName, String pattern) {
        boolean boo = false;
        fileName = FileBaseUtil.getFileNameFront(fileName);
        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_3)) {  //孝义
            //规则  档号 - 件号   0101-912-001-01
            String dj = doc.getArchivalNum() + "-" + doc.getItemNum();
            if (dj.equals(fileName) || doc.getArchivalNum().equals(fileName)) boo = true;

            return boo;
        }


        if (pattern.equals(DicDocPattern.PATTERN_0.getKey())) {//件号匹配
            if (doc.getItemNum().equals(fileName) || (("0" + doc.getItemNum()).equals(fileName))) boo = true;
        }
        if (pattern.equals(DicDocPattern.PATTERN_1.getKey())) {//卷号匹配
            if (doc.getDossierNum().equals(fileName)) boo = true;
        }

        return boo;

    }


    /**
     * @description: 文件名不重复，重复则自动加_数字
     * @author: lig
     * @date: 2021/7/23
     */
    private String notRepeat(ArchivesDoc doc, String fileName) {
        boolean boo = false;
        String ext = "." + FileBaseUtil.getFileNameExt(fileName);
        fileName = FileBaseUtil.getFileNameFront(fileName);
        QueryWrapper<ArchivesDocFile> queryWrapper = new QueryWrapper<ArchivesDocFile>();
        queryWrapper.eq("docId", doc.getId());
        queryWrapper.like("fileName", fileName);
        int i = archivesDocFileMapper.selectCount(queryWrapper);
        if (i > 0) {
            fileName += "_" + i;
        }
        return fileName += ext;
    }

    /**
     * @description: matchingMount  匹配 挂接 文件
     * @author: lig
     * @date: 2021/9/3
     */
    private boolean matchingMount(ArchivesDoc doc, File tempFile, String taskId,String userId) {
        //卷下的件匹配
        if (mountMatching(doc, tempFile.getName(), DicDocPattern.PATTERN_0.getKey())) {
//                                            dossDocs.add(new MountParamDto(tFile, dossierDoc, pattern));
            try {
                buildFile(new MountParamDto(tempFile, doc, DicDocPattern.PATTERN_0.getKey(),userId));
            } catch (Exception e) {
                e.printStackTrace();
                redisUtil.set(taskId, "3:" + e.getMessage(), 60 * 5);
                return false;
            }
        }
        return true;
    }



    public static void main(String[] args) {
        String tempFile = "D:\\home\\jar\\temp\\1417051862665793538\\0002\\002.zip";
        String fileZip = "D:\\home\\jar\\temp\\397\\";
//        ZipUtil.unzip(tempFile, fileZip, Charset.forName("UTF-8"));
//        ZipUtil.unzip(tempFile, fileZip,Charset.forName("GBK"));


//        File downFile = new File(fileZip);
//            System.out.println("22222222222222:"+downFile.getAbsolutePath().indexOf("."));
//        if(downFile.getAbsolutePath().indexOf(".") > 0){
//        }

        File f = new File("http://192.168.1.114:9000/temp/1/file/202108/c54207df-2e54-4f0a-9726-126123346038.xlsx");
        System.out.println("222:" + f.isDirectory());

//        String absolute = "static/0001/2/null/002/535/1222_12.docx";
//        System.out.println("44444444:" + absolute.lastIndexOf(File.separator));
//        System.out.println("44444444:"+absolute.substring(0,absolute.lastIndexOf(File.separator)));


    }

}
